var cmsTab
layui.use(['cmsElem','layer','common','form','cmsMenu','cmsTab'],function(){
    var $ = layui.$,
        cmsElem = layui.cmsElem,
        layer   = layui.layer,
        common  = layui.common,
        form    = layui.form,
        cmsMenu = layui.cmsMenu();// 页面上下文菜单

    //核心操作
    cmsTab = layui.cmsTab({
        top_menu   : '#cms_top_menu',
        left_menu  : '#cms_left_menu',
        cms_elem   : '#cms_tab',
        spreadOne  : true,
        async:false
    });
    // 页面禁止双击选中
    $('body').bind("selectstart", function() {return false;});

    // 菜单初始化
    // 方法1：
    cmsTab.menuSet({
        tyep :'GET',
        url  : 'datas/data.json?t='+Math.random()
    });
    cmsTab.menu();

    // 方法2：
    // $.ajaxSettings.async = false;
    // $.getJSON('datas/data.json?t=' + Math.random(), function(menuData) {
    // CmsTab.menuSet({
    // 	data : menuData,
    // 	topFilter : 'TopMenu',
    // 	lefFilter : 'cmsSide'
    // });
    // CmsTab.menu();
    // });
    // $.ajaxSettings.async = true;

    // 1监听导航菜单点击事件 请注释2
    $('#cms_top_menu li').on('click',function(){
        var group = $(this).children('a').data('group');
        cmsTab.on('click(TopMenu)',group);
        //监听左侧菜单点击事件
        cmsTab.on('click(CmsSide)',group,function(data){
            cmsTab.tabAdd(data.field);
        });
    });
    $('#cms_top_menu li:eq(0)').click();


    // 2若不存在顶级菜单 注释以上顶级菜单监听js
    // CmsTab.on('click(CmsSide)','0', function(data) {
    // 	CmsTab.tabAdd(data.field);
    // });


    // 常用操作
    $('#buttonRCtrl').find('dd').each(function() {
        $(this).on('click', function() {
            var eName = $(this).children('a').attr('data-eName');
            cmsTab.tabCtrl(eName);
        });
    });

    //清除缓存
    $('#clearCached').on('click', function () {
        cmsTab.cleanCached();
        layer.alert('缓存清除完成!本地存储数据也清理成功！', { icon: 1, title: '系统提示' }, function () {
            location.reload();//刷新
        });
    });
    
    $(document).ready(function() {
        var fScreen   = localStorage.getItem("fullscreen_info");
        var themeName = localStorage.getItem('themeName');
        if (themeName) {
            $("body").attr("class", "");
            $("body").addClass("Theme-" + themeName);
        }
        if (fScreen && fScreen != 'false') {
            var fScreenIndex = layer.alert('按ESC退出全屏', {
                title: '进入全屏提示信息',
                skin: 'layui-layer-lan',
                closeBtn: 0,
                anim: 4,
                offset: '100px'
            }, function() {
                entryFullScreen();
                $('#FullScreen').html('<i class="cms-icon cms-quanping"></i>退出全屏');
                layer.close(fScreenIndex);
            });
        }
    });

    // 刷新iframe
    $("#refresh_iframe").click(function() {
        $('#cms_tab_content').children('.layui-show').children('iframe')[0].contentWindow.location.reload(true);
    });

    //主题点击事件
    $('#Theme').on('click', function() {
        var fScreen = localStorage.getItem('fullscreen_info');
        var themeName = localStorage.getItem('themeName');
        layer.open({
            type       : 1,
            title      : false,
            closeBtn   : true,
            shadeClose : false,
            shade      : 0.35,
            area       : ['490px', '365px'],
            isOutAnim  : true,
            resize     : false,
            anim       : Math.ceil(Math.random() * 6),
            content: $('#ThemeSet').html(),
            success: function(layero, index) {
                if (fScreen && fScreen != 'false') {
                    $("input[lay-filter='fullscreen']").attr("checked", "checked");
                }
                if (themeName) {
                    $("#themeName option[value='" + themeName + "']").attr("selected", "selected");
                }
                form.render();
            }
        });

        // 全屏开启
        form.on('switch(fullscreen)', function(data) {
            var fValue = data.elem.checked;
            localStorage.setItem('fullscreen_info', fValue); //fullscreen_info:fValue
        });

        // tabSession开启
        form.on('switch(tabSession)', function(data) {
            var tabS = data.elem.checked;
            localStorage.setItem('tabSessions', tabS); //tabSessions:tabS
        });
        // tab选项卡切换是否自动刷新
        form.on('switch(autoRefresh)',function(data){
            var auto = data.elem.checked;
            localStorage.setItem('autoRefresh', auto);
        });
        // 主题设置
        form.on('select(Theme)', function(data) {
            var themeValue = data.value;
            localStorage.setItem('themeName', themeValue); //themeName:themeValue
            if (themeName) {
                $("body").attr("class", "");
                $("body").addClass("Theme-" + themeName);
            }
            form.render('select');
        });

        return false;
        // 是否存入数据库
        // form.on('submit(submitlocal)',function(data){
        // })
    });

    // 全屏切换
    $('#FullScreen').bind('click', function() {
        var fullscreenElement =
            document.fullscreenElement ||
            document.mozFullScreenElement ||
            document.webkitFullscreenElement;
        if (fullscreenElement == null) {
            entryFullScreen();
            $(this).html('<i class="cms-icon">&#xe604;</i>退出全屏');
        } else {
            exitFullScreen();
            $(this).html('<i class="cms-icon">&#xe604;</i>全屏');
        }
    });

    // 登出系统
    $('#logout').on('click',function(){
        var url ='login.html';
        console.log(url);
        common.logOut('退出登陆提示！','你真的确定要退出系统吗？',url);
    });
    /*
        var cmsMenuData = [
            [{
                text: "刷新当前页",
                func: function() {
                    $(".layui-tab-content .layui-tab-item").each(function() {
                        if ($(this).hasClass('layui-show')) {
                            $(this).children('iframe')[0].contentWindow.location.reload(true);
                        }
                    });
                }
            },{
                text: "重载主框架",
                func: function() {
                    document.location.reload();
                }
            },{
                text: "设置系统主题",
                func: function() {
                    $("#Theme").trigger("click");
                }
            }, {
                text: "选项卡常用操作",
                data: [
                    [{
                        text: "定位当前选项卡",
                        func: function() {
                            $("#tabCtrD").trigger("click");
                        }
                    },{
                        text: "关闭当前选项卡",
                        func: function() {
                            $("#tabCtrA").trigger("click");
                        }
                    }, {
                        text: "关闭其他选项卡",
                        func: function() {
                            $("#tabCtrB").trigger("click");
                        }
                    }, {
                        text: "关闭全部选项卡",
                        func: function() {
                            $("#tabCtrC").trigger("click");
                        }
                    }]
                ]
            }],
        ];
        cmsMenu.ContentMenu(cmsMenuData,{name: "body"},$('body'));
        $('#cms_body').mouseover(function(){cmsMenu.remove();});
    */

    $('.pressKey').on('click', function() {
        var titW = parseInt($('#cms_tab').width() - 270);
        var $tabUl = $('#cms_tab').find('li'),
            all_li_w = 0;
        $tabUl.each(function(i, n) {
            all_li_w += $(n).outerWidth(true);
        });
        if (titW >= all_li_w) {
            layer.tips('当前没有可移动的选项卡！', $(this), {
                tips: [3, '#FF5722']
            });
        }
    });

    // 支持作者
    $('#dianzhan').click(function(event) {
        layer.open({
            type: 1,
            title: false,
            closeBtn: true,
            shadeClose: false,
            shade: 0.75,
            area: ['520px', '288px;'],
            content: '<img src="images/dianzhan.jpg"/>'
        })
    });

    // 兼容蛋疼的移动端
    $('#cmsMobile').on('click', function() {
        if ($('.cms-mobile #cms_left').css("display") == "none") {
            $('.cms-mobile #cms_left').show();
        } else {
            $('.cms-mobile #cms_left').hide();
        }

        if ($('.cms-mobile .cms-top-menu').css("display") == "none") {
            $('.cms-mobile .cms-top-menu').show();
        } else {
            $('.cms-mobile .cms-top-menu').hide();
        }

    });

    var device = layui.device();
    // 兼容IE8 chrome 60以下版本 calc
    if(device.ie && device.ie <9){
        $('.cms-top').width($('#cms_admin_out').width()-200);
    }else if(navigator.userAgent.indexOf("Chrome") <= 60 && navigator.userAgent.indexOf("Chrome") > -1){
        $('.cms-top').width($('#cms_admin_out').width()-200);
    }
    // 锁屏控制提示
    $('#lock').mouseover(function(){
        layer.tips('请按Alt+L快速锁屏！', '#lock', {
            tips: [1, '#FF5722'],
            time: 1500
        });
    });

    $(document).keydown(function() {
        return key(arguments[0])
    });

    // 点击锁屏
    $('#lock').click(function(){lockSystem();});

    // 解锁进入系统
    $('#unlock').click(function(){unlockSys();});

    // 监控lock_password 键盘事件
    $('#unlock_pass').keypress(function(e){
        if (window.event && window.event.keyCode == 13) {
            unlockSys();
            return false;
        }
    });

    // 锁定屏幕
    var locked = 0;
    function lockSystem(){
        var url = 'datas/lock.php';
        locked = 1;
        $.post(
            url,
            function(data){
                if(data.lock){
                    checkLockStatus(locked);
                }else{
                    layer.alert('锁屏失败，请稍后再试！');
                }
            },
            "json"
        );
        startTimer();

    }
    function unlockSys(){
        if($('#unlock_pass').val() == 'larrycms'){
            locked = 0;
            checkLockStatus(locked);
            return;
        }else{
            layer.tips('模拟锁屏，输入密码：larrycms 解锁', $('#unlock'), {
                tips: [3, '#FF5722'],
                time:1000
            });
            return;
        }
    }
    // 锁屏状态检测
    function checkLockStatus(locked){
        // 锁屏
        if(locked == 1){
            $('.lock-screen').show();
            $('#locker').show();
            $('#cms_admin_out').hide();
            $('#lock_password').val('');
        }else{
            $('.lock-screen').hide();
            $('#locker').hide();
            $('#cms_admin_out').show();
        }
    }
    function key(e) {
        var keynum;
        if (window.event) {
            keynum = e.keyCode;
        } else if (e.which) {
            keynum = e.which;
        }
        if(e.altKey && keynum == 76){
            lockSystem();
        }
    }
    function startTimer(){
        var today=new Date();
        var h=today.getHours();
        var m=today.getMinutes();
        var s=today.getSeconds();
        m = m < 10 ? '0' + m : m;
        s = s < 10 ? '0' + s : s;
        $('#time').html(h+":"+m+":"+s);
        t=setTimeout(function(){startTimer()},500);
    }
});
function LockClick(){
    //setTimeout(function() {
    document.getElementById("lock").click();
    //},1);
}

// 进入全屏：
function entryFullScreen() {
    var docE = document.documentElement;
    if (docE.requestFullScreen) {
        docE.requestFullScreen();
    } else if (docE.mozRequestFullScreen) {
        docE.mozRequestFullScreen();
    } else if (docE.webkitRequestFullScreen) {
        docE.webkitRequestFullScreen();
    }
}

// 退出全屏
function exitFullScreen() {
    var docE = document;
    if (docE.exitFullscreen) {
        docE.exitFullscreen();
    } else if (docE.mozCancelFullScreen) {
        docE.mozCancelFullScreen();
    } else if (docE.webkitCancelFullScreen) {
        docE.webkitCancelFullScreen();
    }
}